package com.das.mechanic_base.mvp.presenter.sivetain;

import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BaseCallModel;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.common.UploadVideoBean;
import com.das.mechanic_base.bean.create.ServiceInfoBean;
import com.das.mechanic_base.bean.live.FetchLiveBean;
import com.das.mechanic_base.bean.live.LiveCarListBean;
import com.das.mechanic_base.bean.maintain.AdvanceTimeBean;
import com.das.mechanic_base.bean.maintain.CancelWorkBean;
import com.das.mechanic_base.bean.maintain.WorkBaseHeaderBean;
import com.das.mechanic_base.bean.processsive.ProcessSiveTempLetBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.mvp.contract.sivetain.IntentSiveContract;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 作者：zhanglei on 2020-03-20 10:23
 * <p>
 * 邮箱：916256628@qq.com
 */
public class IntentSivePrestener extends X3BasePresenter<IntentSiveContract.View> implements IntentSiveContract.Presenter {

    private int status;
    private Disposable disposable;

    /**
     * 校验技师是否串工位
     */
    @Override
    public void obtainWorkBase() {
        NetWorkHttp.getApi().obtainWorkBaseValidate(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<X3BaseCallModel<Boolean>>defaultComposeRequest())
                .subscribe(new HttpCallBack<Boolean>() {
                    @Override
                    protected void onDone(Boolean isInTo) {
                        mView.setContainMe(isInTo);
                        requestAdavance();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.setContainMeFail();
                    }
                });
    }

    @Override
    public void startStoreLiveRoom() {
        disposable = Observable.interval(5,5, TimeUnit.SECONDS)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.<Long>defaultComposeRequest())
                .doOnNext(aLong -> {
                    // 轮询任务
                    getLiveNum();
                }).subscribe();
    }

    @Override
    public void completeWorkBase(long id) {
        NetWorkHttp.getApi().obtainCompleteWork(id)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {

                        mView.jumpComplete();

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        if (mView instanceof X3BaseActivity){
                            ((X3BaseActivity)mView).hideLoading();
                        }
                    }
                });
    }


    /**
     * 获取当前正在直播的数量
     */
    private void getLiveNum() {
        NetWorkHttp.getApi().listStoreLiveRoom()
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new Observer<X3BaseCallModel<List<LiveCarListBean>>>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable disposable) {

                    }

                    @Override
                    public void onNext(@NotNull X3BaseCallModel<List<LiveCarListBean>> listBaseCallModel) {
                        int status = listBaseCallModel.status;
                        mView.getStoreLiveRoomSuccess(0);
                        if (status == 0) {
                            List<LiveCarListBean> liveCarListBeans = listBaseCallModel.data;
                            if (X3StringUtils.isListEmpty(liveCarListBeans)) {
                                mView.getStoreLiveRoomSuccess(0);
                                return;
                            }
                            mView.getStoreLiveRoomSuccess(liveCarListBeans.size());
                        }
                    }

                    @Override
                    public void onError(@NotNull Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void endStoreLiveRoom() {
        if (disposable == null || disposable.isDisposed()) {
            return;
        }
        disposable.dispose();
    }

    @Override
    public void getCancelWork() {

        NetWorkHttp.getApi().obtainListReceive(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CancelWorkBean>>() {
                    @Override
                    protected void onDone(List<CancelWorkBean> cancelWorkBeans) {
                        mView.requestCancelWorkSuccess(cancelWorkBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void affirmCancelWork(List<CancelWorkBean> mList, boolean isOne) {

        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            idList.add(mList.get(i).getReceiveVariantId());
        }

        NetWorkHttp.getApi().obtainCancelWork(idList)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {

                        if (!isOne) {
                            // 如果是最后一个取消的话 相当于施工单已经不存在 这时候刷新的话会报错 所....
//                            refresh();
                            List<String> serviceList = new ArrayList<>();
                            for (CancelWorkBean workBean : mList) {
                                serviceList.add(workBean.getServiceBaseName());
                            }
                            mView.changeServiceName(serviceList);
                        } else {
                            mView.finishCurrent();
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        X3ToastUtils.showMessage(error + "");
                    }
                });
    }

    @Override
    public void updateAdavancService(long id) {
        NetWorkHttp.getApi().obtainUpdateStartTime(mView.providerWorkBaseId())
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<AdvanceTimeBean>() {
                    @Override
                    protected void onDone(AdvanceTimeBean advanceTimeBean) {
                        mView.updateAfterWork(true, advanceTimeBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    public void showErrorStatus(int status) {
                        if (1101 == status) {
                            requestAdavance();
                        }
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void requestAdavance() {
        //第一步--获取当前页面的数据
        NetWorkHttp.getApi().getWorkBaseHeader(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<WorkBaseHeaderBean>() {
                    @Override
                    protected void onDone(WorkBaseHeaderBean headerBean) {
                        if (headerBean == null) {
                            return;
                        }
                        mView.getWorkBaseHeaderInfo(headerBean);
                       // checkStatus(headerBean.getWorkBaseStatus());
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mView.getWorkBaseHeaderInfoFail();
                    }
                });
    }

    @Override
    public void validStartStep(String technicSn) {

        NetWorkHttp.getApi().validProceStep(technicSn,mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.<X3BaseCallModel<Boolean>>defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<Boolean>() {

                    @Override
                    protected void onDone(Boolean o) {
                        mView.validStartStepSuccess(o);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }
//
//    private void checkStatus(int status) {
//        this.status = status;
//        /**
//         * 0 预约单
//         * 1 施工单
//         */
//        int id = mView.providerWorkBaseId();
//        NetWorkHttp.getApi().obtainWorkBaseValidate(id)
//                .compose(RxSchedulersHelper.<BaseCallModel<Boolean>>defaultComposeRequest())
//                .subscribe(new HttpCallBack<Boolean>() {
//                    @Override
//                    protected void onDone(Boolean isInTo) {
//                        if (isInTo) {
//                            // 正常进入
//                            requestTainMain();
//                        } else {
//                            // 不允许进入   技师不属于当前工位 或者当前施工单 不允许进入
//                            mView.cancelButton();
//                        }
//                    }
//
//                    @Override
//                    protected String LoadingMessage() {
//                        return null;
//                    }
//
//                    @Override
//                    protected void showError(String error) {
//                        ToastUtils.showMessage(error + "");
//                    }
//                });
//    }

    @Override
    public void requestTainMain() {
        long id = mView.providerWorkBaseId();
        NetWorkHttp.getApi().getTechnicsTempletListByWorkBaseId(id)
                .compose(mView.bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<ProcessSiveTempLetBean>>() {

                    @Override
                    protected void onDone(List<ProcessSiveTempLetBean> processSiveTempLetBeans) {
                        mView.saveTechnicsTempletList(processSiveTempLetBeans);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                    }
                });
    }

    @Override
    public void generateLiveInfoOnLocal(long carId, boolean isCarOwnerRequired, long workBaseId) {
        NetWorkHttp.getApi().generateLiveInfoOnLocal(carId, isCarOwnerRequired, workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<FetchLiveBean>() {
                    @Override
                    protected void onDone(FetchLiveBean fetchLiveBean) {
                        if (fetchLiveBean != null) {
                            mView.getLiveInfoSuccess(fetchLiveBean);
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void listLiveUploadVideo(long workBaseId) {
        NetWorkHttp.getApi().listLiveUploadVideo(workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<List<UploadVideoBean>>() {
                    @Override
                    protected void onDone(List<UploadVideoBean> uploadVideoBean) {
                        mView.getUploadVideoSuccess(uploadVideoBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @Override
    public void getWorkBase() {
        NetWorkHttp.getApi().getWorkBase(mView.providerWorkBaseId())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(mView.bindToLife())
                .subscribe(new HttpCallBack<ServiceInfoBean.WorkBaseBean>() {
                    @Override
                    protected void onDone(ServiceInfoBean.WorkBaseBean workBaseBean) {
                        mView.getWorkBaseSuccess(workBaseBean);
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }
}
